package com.xbongbong.saas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.elasticsearch.constant.EsNormalConstant;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.help.ProSaveHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.log.pojo.InfoArrPojo;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasProcessTemplateModel;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.pojo.AttrValuePojo;
import com.xbongbong.paas.pojo.FieldAttrEntityForImport;
import com.xbongbong.paas.pojo.FormTitlePoJo;
import com.xbongbong.paas.pojo.SummaryDataPoJo;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.dto.ImportFormDataDTO;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.pojo.imports.CellTitlePojo;
import com.xbongbong.paas.pojo.imports.CellValuePojo;
import com.xbongbong.paas.pojo.imports.RowGroupPojo;
import com.xbongbong.paas.service.team.TeamDataHelp;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.PageHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.applist.pojo.AppListPojo;
import com.xbongbong.pro.applist.pojo.vo.ListAppVO;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.ClueErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.UserTeamErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.AfterSavePojo;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainInLinkItemDTO;
import com.xbongbong.pro.listbatch.pojo.dto.AddLabelDTO;
import com.xbongbong.pro.marketManage.pojo.dto.MarketActivityDeleteBatchDTO;
import com.xbongbong.pro.marketManage.pojo.dto.MarketActivityEditAttrUpdateDTO;
import com.xbongbong.pro.marketManage.pojo.dto.MarketActivitySearchDTO;
import com.xbongbong.pro.marketManage.pojo.dto.MarketActivityUpdateBatchDTO;
import com.xbongbong.pro.marketManage.pojo.dto.MarketActivityUpdateDTO;
import com.xbongbong.pro.marketManage.pojo.dto.MarketActivityUserDeleteBatchDTO;
import com.xbongbong.pro.marketManage.pojo.vo.MarketActivityDeleteBatchVO;
import com.xbongbong.pro.marketManage.pojo.vo.MarketActivityEditAttrUpdateVO;
import com.xbongbong.pro.marketManage.pojo.vo.MarketActivitySearchVO;
import com.xbongbong.pro.marketManage.pojo.vo.MarketActivityUpdateBatchVO;
import com.xbongbong.pro.thread.ThreadPoolBeanConfig;
import com.xbongbong.saas.analytical.impl.MarketActivityValidateAnalyticalServiceImpl;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.PageConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.StaticForUpdateDTO;
import com.xbongbong.saas.domain.entity.ext.MarketActivityEntityExt;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.MarketActivityEnum;
import com.xbongbong.saas.help.ImportHelper;
import com.xbongbong.saas.help.LogHandleHelp;
import com.xbongbong.saas.help.workflow.MarketActivityForStaticHelp;
import com.xbongbong.saas.model.MarketActivityModel;
import com.xbongbong.saas.model.MarketActivityUserModel;
import com.xbongbong.saas.service.MarketActivityForStaticService;
import com.xbongbong.saas.service.MarketActivityService;
import com.xbongbong.saas.service.MarketActivityUserService;
import com.xbongbong.saas.service.UserTeamService;
import com.xbongbong.saas.service.toolbox.help.LogHelp;
import com.xbongbong.saas.service.toolbox.help.UserTeamHelp;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @author haibing.zhang
 * @version v1.0
 * @date 2019/1/18
 * @since v1.0
 */
@Service("marketActivityService")
public class MarketActivityServiceImpl implements MarketActivityService {

    @Resource
    private MarketActivityModel marketActivityModel;
    @Resource
    private PaasProcessTemplateModel paasProcessTemplateModel;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private EsHelper esHelper;
    @Resource
    private MarketActivityUserService marketActivityUserService;
    @Resource
    private UserTeamService userTeamService;
    @Resource
    private ThreadPoolBeanConfig threadPoolBeanConfig;
    @Resource
    private LogHelp logHelp;
    @Resource
    private ImportHelper importHelper;
    @Resource
    private MarketActivityForStaticService marketActivityForStaticService;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private LogHandleHelp logHandleHelp;
    @Resource
    private MarketActivityValidateAnalyticalServiceImpl marketActivityAnalyticalService;
    @Resource
    private MarketActivityUserModel marketActivityUserModel;
    @Resource
    private TeamDataHelp teamDataHelp;
    @Resource
    private UserTeamHelp userTeamHelp;
    @Resource
    private MarketActivityForStaticHelp marketActivityForStaticHelp;


    private static final Logger LOG = LoggerFactory.getLogger(MarketActivityServiceImpl.class);

    /**
     *
     * @param validateDataDTO saas特殊校验数据入参
     * @throws XbbException
     */
    @Override
    public void beforeSave(ValidateDataDTO validateDataDTO) throws XbbException {
        marketActivityAnalyticalService.beforeSave(validateDataDTO);
    }


    @Override
    public AfterSavePojo afterSave(SaasFormSaveDTO saasFormSaveDTO) throws XbbException {
        AfterSavePojo afterSavePojo = new AfterSavePojo();
        JSONObject newData = saasFormSaveDTO.getNewData();
        JSONObject oldData = saasFormSaveDTO.getOldData();
        PaasFormDataEntity newPaasFormDataEntity = saasFormSaveDTO.getNewPaasFormDataEntity();
        Long dataId = newPaasFormDataEntity.getId();

        // 团队保存
        afterSavePojo = teamDataHelp.saveUserTeam(saasFormSaveDTO.getSaasNeedRedundantAttrPoJo(), dataId, newPaasFormDataEntity, saasFormSaveDTO.getIsImport(), false);
        //保存团队
//        SaasNeedRedundantAttrPojo saasNeedRedundantAttrPoJo = saasFormSaveDTO.getSaasNeedRedundantAttrPoJo();
//        if (Objects.nonNull(saasNeedRedundantAttrPoJo)) {
//            BeforeSaveMyTeamDTO beforeSaveMyTeamDTO = saasNeedRedundantAttrPoJo.getBeforeSaveMyTeamDTO();
//            beforeSaveMyTeamDTO.setDataId(dataId);
//            UserTeamBatchSaveDTO userTeamBatchSaveDTO = userTeamService.beforeSaveMyTeam(beforeSaveMyTeamDTO);
//            userTeamBatchSaveDTO.setLoginUser(saasFormSaveDTO.getLoginUser());
//            userTeamService.saveMyTeam(userTeamBatchSaveDTO);
//        }
//        Runnable runnable = () -> {
//            if (isNew) {
//                String creatorId = newPaasFormDataEntity.getCreatorId();
//                UserEntity creatorUser = userModel.getByKey(creatorId, corpid);
//                try {
//                } catch (Exception e) {
//                    LOG.error("机会创建项目日志", e);
//                }
//
//            }
//
//        };
//        threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable);

        return afterSavePojo;
    }

    @Override
    public void formatData(SaasAnalysisDataDTO saasAnalysisDataDTO, JSONObject result) throws XbbException {

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MarketActivityEditAttrUpdateVO batchEditAttr(MarketActivityEditAttrUpdateDTO marketActivityEditAttrUpdateDTO) throws XbbException {
        MarketActivityEditAttrUpdateVO marketActivityEditAttrUpdateVO = new MarketActivityEditAttrUpdateVO();
        try {
            Map<String, Object> param = BeanUtil.convertBean2Map(marketActivityEditAttrUpdateDTO, true);
            param.put("idIn", marketActivityEditAttrUpdateDTO.getDataIdList());
            List<MarketActivityEntityExt> marketActivityList = marketActivityModel.findEntitys(param);
            if(Objects.isNull(marketActivityList)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
            }
            //权限团队校验前置了
            List<Long> errorIdList = new ArrayList<>();
//            List<Long> errorIdList = userTeamHelp.batchTeamMembersCheckEditPermission(marketActivityEditAttrUpdateDTO.getBusinessType(), marketActivityEditAttrUpdateDTO.getSaasMark(),
//                    marketActivityEditAttrUpdateDTO.getMenuId(), marketActivityEditAttrUpdateDTO.getLoginUser(), marketActivityEditAttrUpdateDTO.getDistributorMark(),
//                    marketActivityEditAttrUpdateDTO.getDataIdList(), new HashMap<>());
            List<String> errorNameList = new ArrayList<>();
            for (MarketActivityEntityExt marketActivityEntityExt : marketActivityList) {
                if (errorIdList.contains(marketActivityEntityExt.getId())) {
                    errorNameList.add(marketActivityEntityExt.getData().getString(MarketActivityEnum.NAME.getAttr()));
                }
            }
            String nameStr = org.apache.commons.lang.StringUtils.join(errorNameList, "、");
            if (CollectionUtils.isNotEmpty(errorNameList)) {
                throw new XbbException(UserTeamErrorCodeEnum.API_ERROR_271038.getCode(), String.format(UserTeamErrorCodeEnum.API_ERROR_271038.getMsg(), nameStr));
            }
            //市场活动的开始时间不能晚于结束时间
            verificationEditData(marketActivityEditAttrUpdateDTO);
            List<Long> updateIdList = new ArrayList<>();
            List<MarketActivityUpdateDTO> marketActivityUpdateList = new ArrayList<>();
            marketActivityEditAttrUpdateDTO.getDataIdList().forEach((item)->{
                MarketActivityUpdateDTO marketActivityUpdateDTO = new MarketActivityUpdateDTO();
                marketActivityUpdateDTO.setId(item);
                updateIdList.add(item);
                JSONObject data = ProSaveHelp.getBatchUpdateData(marketActivityEditAttrUpdateDTO.getFieldEditedList());
                marketActivityUpdateDTO.setData(data);
                marketActivityUpdateList.add(marketActivityUpdateDTO);
            });
            if (!marketActivityUpdateList.isEmpty()) {
                MarketActivityUpdateBatchDTO marketActivityUpdateBatchDTO = new MarketActivityUpdateBatchDTO();
                BeanUtil.copyProperties(marketActivityEditAttrUpdateDTO, marketActivityUpdateBatchDTO);
                marketActivityUpdateBatchDTO.setMarketActivityList(marketActivityUpdateList);
                marketActivityUpdateBatch(marketActivityUpdateBatchDTO);
                marketActivityEditAttrUpdateVO.setUpdateIdList(updateIdList);
            }
            // 批量编辑日志
            List<String> updataItemList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            List<Long> dataIdList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (MarketActivityEntityExt item : marketActivityList) {
                dataIdList.add(item.getId());
                JSONObject data = item.getData();
                String serialNo = item.getSerialNo();
                String opObjectName = data.getString(MarketActivityEnum.NAME.getAttr());
                StringBuilder sb = new StringBuilder();
                opObjectName = opObjectName == null ? serialNo : sb.append(serialNo).append("（").append(opObjectName).append("）").toString();
                updataItemList.add(opObjectName);
            }
            String updataItem = StringUtils.join(updataItemList, "，");
            String userId = marketActivityEditAttrUpdateDTO.getUserId();
            String corpid = marketActivityEditAttrUpdateDTO.getCorpid();
            String loginUserName = marketActivityEditAttrUpdateDTO.getLoginUserName();
            // 标签特殊处理
            Integer fieldType = marketActivityEditAttrUpdateDTO.getFieldType();
            Boolean isFieldDependence = marketActivityEditAttrUpdateDTO.getIsFieldDependence();
            logHelp.analysisLabel(corpid, fieldType, isFieldDependence,marketActivityEditAttrUpdateDTO.getLogFieldEditedList());

            String changedLogItemsStr = logHandleHelp.getChangedLogItemsStr(marketActivityEditAttrUpdateDTO.getLogFieldEditedList());
            if(dataIdList.size() > 1 ){
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_FORM_DATA_BATCH_ATTR), loginUserName, XbbRefTypeEnum.MARKET_ACTIVITY.getName(),
                        changedLogItemsStr, dataIdList.size());
                List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                InfoArrPojo infoArrPojo = new InfoArrPojo();
                infoArrPojo.setTitle(XbbRefTypeEnum.MARKET_ACTIVITY.getName());
                infoArrPojo.setContent(updataItem);
                infoArrPojoList.add(infoArrPojo);
                mongoLogHelp.buildLog4InfoArr(infoArrPojoList, corpid, userId, loginUserName, OperateModuleTypeEnum.MARKET_ACTIVITY, OperateTypeEnum.EDIT,
                        "", "", memo, marketActivityEditAttrUpdateDTO.getHttpHeader());
            } else if (Objects.equals(dataIdList.size(), 1)){
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_FORM_DATA_ATTR), loginUserName, XbbRefTypeEnum.MARKET_ACTIVITY.getName(), updataItem,
                        changedLogItemsStr);
                mongoLogHelp.buildLog(corpid, userId, loginUserName, OperateModuleTypeEnum.MARKET_ACTIVITY, OperateTypeEnum.EDIT,
                        dataIdList.get(0).toString(), updataItem, memo, marketActivityEditAttrUpdateDTO.getHttpHeader());
            }
        } catch (XbbException e){
            throw e;
        } catch (Exception e) {
            LOG.error("MarketActivityServiceImpl.batchEditAttr 执行出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return marketActivityEditAttrUpdateVO;
    }
    private void verificationEditData(MarketActivityEditAttrUpdateDTO marketActivityEditAttrUpdateDTO) throws XbbException {
        if(Objects.nonNull(marketActivityEditAttrUpdateDTO) && CollectionsUtil.isNotEmpty(marketActivityEditAttrUpdateDTO.getDataIdList())){
            List<Long> dataIdList = marketActivityEditAttrUpdateDTO.getDataIdList();
            List<MarketActivityEntityExt> marketActivityEntityExtList = marketActivityModel.getByKeys(dataIdList, marketActivityEditAttrUpdateDTO.getCorpid());
            if(CollectionsUtil.isEmpty(marketActivityEntityExtList)){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018,"编辑的数据不存在");
            }
            Boolean isFieldDependence = marketActivityEditAttrUpdateDTO.getIsFieldDependence();
            if (isFieldDependence) {
                return;
            }
            // 觉得attr 不是可以直接return
            AttrValuePojo singleAttrValuePojo = ProSaveHelp.getSingleAttrValuePojo(isFieldDependence, marketActivityEditAttrUpdateDTO.getFieldEditedList());
            for(MarketActivityEntityExt marketActivityEntityExt : marketActivityEntityExtList){
                JSONObject data = marketActivityEntityExt.getData();
                Long value = Objects.nonNull(singleAttrValuePojo.getValue()) && (singleAttrValuePojo.getValue() instanceof Integer) ? ((Integer) singleAttrValuePojo.getValue()).longValue() : 0;
                if(Objects.nonNull(data) && Objects.nonNull(value) && ((Number)value).longValue() != 0L){
                    //data.get()解析出来是
                    Long startTime = Objects.isNull(data.get(MarketActivityEnum.START_TIME.getAttr())) ? 0L : data.getLongValue(MarketActivityEnum.START_TIME.getAttr());
                    Long endTime = Objects.isNull(data.get(MarketActivityEnum.END_TIME.getAttr())) ? 0L : data.getLongValue(MarketActivityEnum.END_TIME.getAttr());
                    //开始时间 和 结束时间 都不为空时，再去判断“开始时间晚于结束时间” 这个条件
                    if(startTime != 0L  &&  endTime !=0L ){
                        //开始时间晚于结束时间
                        if ((MarketActivityEnum.START_TIME.getAttr().equals(singleAttrValuePojo.getAttr()) && value > endTime)
                                || (MarketActivityEnum.END_TIME.getAttr().equals(singleAttrValuePojo.getAttr()) && (Long) value < startTime)) {
                            throw new XbbException(ClueErrorCodeEnum.API_ERROR_1100200);
                        }
                    }
                }

            }

        }
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public MarketActivityUpdateBatchVO marketActivityUpdateBatch(MarketActivityUpdateBatchDTO marketActivityUpdateBatchDTO) throws XbbException {
        MarketActivityUpdateBatchVO marketActivityUpdateBatchVO = new MarketActivityUpdateBatchVO();
        try {
            String corpid = marketActivityUpdateBatchDTO.getCorpid();
            List<UpdateDataEntity> updateList = new ArrayList<>();
            List<MarketActivityUpdateDTO> marketActivityUpdateList = marketActivityUpdateBatchDTO.getMarketActivityList();
            if (Objects.nonNull(marketActivityUpdateList) && !marketActivityUpdateList.isEmpty()) {
                marketActivityUpdateList.forEach((item)->{
                    updateList.add(ExplainUtil.getUpdateData(item.getId(), item.getData(), corpid));
                });
            }
            if (!updateList.isEmpty()) {
                marketActivityModel.updateBatch(updateList, corpid);
            }
            dealStaticMarket(corpid, marketActivityUpdateList);
        } catch (Exception e) {
            LOG.error("marketActivityServiceImpl.marketActivityUpdateBatch 执行出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return marketActivityUpdateBatchVO;
    }

    /**
     * 处理编辑接口(市场活动统计中间表)
     * @param corpid
     * @param marketActivityUpdateList
     */
    public void dealStaticMarket(String corpid, List<MarketActivityUpdateDTO> marketActivityUpdateList) throws XbbException{
        List<StaticForUpdateDTO> list = new ArrayList<>();
        for (MarketActivityUpdateDTO marketActivityUpdateDTO : marketActivityUpdateList) {
            StaticForUpdateDTO staticForUpdateDTO = new StaticForUpdateDTO();
            BeanUtil.copyProperties(marketActivityUpdateDTO, staticForUpdateDTO);
            list.add(staticForUpdateDTO);
        }
        marketActivityForStaticHelp.updateBatchMarketActivity(list, XbbRefTypeEnum.MARKET_ACTIVITY ,corpid);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public MarketActivityDeleteBatchVO deleteBatch(MarketActivityDeleteBatchDTO marketActivityDeleteBatchDTO) throws XbbException {
        MarketActivityDeleteBatchVO marketActivityDeleteBatchVO= new MarketActivityDeleteBatchVO();
        try {
            List<Long> idIn = marketActivityDeleteBatchDTO.getDataIdList();
            String corpid = marketActivityDeleteBatchDTO.getCorpid();
            Map<String, Object> param = BeanUtil.convertBean2Map(marketActivityDeleteBatchDTO, true);
            param.put("idIn", idIn);
            List<MarketActivityEntityExt> marketActivityList = marketActivityModel.findEntitys(param);
            if (CollectionsUtil.isEmpty(marketActivityList)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100404);
            }

            //查询名称
            List<String> nameList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            BoolQueryBuilder marketActivityBuilder = new BoolQueryBuilder();
            // 添加corpid,formId,del
            marketActivityBuilder.filter(termQuery("corpid.keyword", corpid));
            marketActivityBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
            marketActivityBuilder.filter(termsQuery(StringConstant.DATA_ID, idIn));
            List<String> fieldList = new ArrayList<>();
            fieldList.add(FieldTypeEnum.SERIALNO.getAlias());
            fieldList.add(MarketActivityEnum.getAttrConnectData(MarketActivityEnum.NAME));
            List<PaasFormDataEntityExt> marketActivityExtList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_MARKET_ACTIVITY, marketActivityBuilder, PaasFormDataEntityExt.class, fieldList);
            for(PaasFormDataEntityExt marketActivity : marketActivityExtList){
                JSONObject data = marketActivity.getData();
                String name = FastJsonHelper.getStringOrDefaultFromFormData(data, MarketActivityEnum.NAME.getAttr(), "");
                nameList.add(name);
            }
            // 删除市场活动
            if(!idIn.isEmpty()) {
                if(BasicConstant.ONE.equals(marketActivityDeleteBatchDTO.getSingleFlag())
                        && BasicConstant.ONE.equals(idIn.size())){
                    marketActivityModel.deleteByKey(idIn.get(0),corpid);
                }else {
                    marketActivityModel.deleteBatch(idIn, corpid);
                }
                marketActivityDeleteBatchDTO.setDataIdList(idIn);
                marketActivityForStaticHelp.deleteBatchMarketActivity(idIn, XbbRefTypeEnum.MARKET_ACTIVITY ,corpid, DelEnum.DELETE.getDel());
            }
            marketActivityDeleteBatchVO.setDeleteIds(idIn);
            // 删除市场活动团队关系
            MarketActivityUserDeleteBatchDTO marketActivityUserDeleteBatchDTO = new MarketActivityUserDeleteBatchDTO();
            BeanUtil.copyProperties(marketActivityDeleteBatchDTO, marketActivityUserDeleteBatchDTO);
            marketActivityUserDeleteBatchDTO.setDataIdIn(idIn);
            marketActivityUserService.deleteBatch(marketActivityUserDeleteBatchDTO);
            OperateTypeEnum operateTypeEnum = OperateTypeEnum.DELETE;
            if (Objects.equals(1, marketActivityDeleteBatchDTO.getIsBusinessRule())) {
                operateTypeEnum = OperateTypeEnum.RULE_DELETE;
            }
            //生成删除日志(区分单个删除和批量删除)
            String userId = marketActivityDeleteBatchDTO.getUserId();
            String userName = marketActivityDeleteBatchDTO.getLoginUserName();

            String nameStr = StringUtils.join(nameList, "，");
            if(idIn.size() > 1){
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_DELETE_FORM_DETAIL), userName, XbbRefTypeEnum.MARKET_ACTIVITY.getName(), idIn.size());
                List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                InfoArrPojo infoArrPojo = new InfoArrPojo();
                infoArrPojo.setTitle(MarketActivityEnum.NAME.getAttrName());
                infoArrPojo.setContent(nameStr);
                infoArrPojoList.add(infoArrPojo);
                //操作日志
                mongoLogHelp.buildLog4InfoArr(infoArrPojoList, corpid, userId, userName, OperateModuleTypeEnum.MARKET_ACTIVITY, operateTypeEnum,
                        "", "", memo, marketActivityDeleteBatchDTO.getHttpHeader());
            } else if (Objects.equals(idIn.size(), 1)){
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DELETE_WORK), userName, XbbRefTypeEnum.MARKET_ACTIVITY.getName(), nameStr);
                mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.MARKET_ACTIVITY, operateTypeEnum,
                        idIn.get(0).toString(), nameStr, memo, marketActivityDeleteBatchDTO.getHttpHeader());
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("marketActivityServiceImpl.deleteBatch 执行出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return marketActivityDeleteBatchVO;
    }

    @Override
    public ListAppVO formatMarketActivityAppList(FormDataListDTO formDataListDTO, List<PaasFormDataEntityExt> esEntities, Integer totalCount) throws XbbException {
        if (totalCount == null || totalCount == 0) {
            return new ListAppVO();
        }
        List<AppListPojo> appListPojos = new ArrayList<>();
        String corpid = formDataListDTO.getCorpid();

        List<Long> marketActivityIn = esEntities.stream().map(entity -> entity.getDataId()).collect(Collectors.toList());
        //协同团队
        Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        userTeamService.getUserIdMap(marketActivityIn,corpid,formDataListDTO.getBusinessType(),false ,mainUserMap,coUserMap);
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        BeanUtil.copyProperties(formDataListDTO, handlerExplainDTO);
        //详情 摘要 标签 处理
        JSONObject defaultJson = new JSONObject();
        for(PaasFormDataEntityExt marketActivityEntity : esEntities){
            long id = marketActivityEntity.getDataId();
            long appId = marketActivityEntity.getAppId();
            long menuId = marketActivityEntity.getMenuId();
            long formId = marketActivityEntity.getFormId();
            JSONObject data = marketActivityEntity.getData();


            List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
            List<SummaryDataPoJo> lablesList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.LABELS_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
            List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);
            //app系统关联数据展示时，前端需要 others 信息用来判断
            data.put("others",defaultJson);
            data.put("superScript" ,defaultJson);
            appListPojos.add(new AppListPojo(id, titleList, summaryList, defaultJson, lablesList, defaultJson, appId, menuId, formId));
        }
        ListAppVO listAppVO = new ListAppVO();
        listAppVO.setList(appListPojos);
        listAppVO.setTotalCount(totalCount);
        return  listAppVO;
    }

    @Override
    public void formatAddExplain(FormatExplainDTO formatExplainDTO) throws XbbException {
        //暂时没有需要处理的
//        if (Objects.equals(formatExplainDTO.getSubBusinessType(), XbbRefTypeEnum.MARKET_ACTIVITY.getCode())) {
//            List<FieldAttrEntity> explainList = formatExplainDTO.getExplainList();
//            for (FieldAttrEntity fieldAttrEntity : explainList) {
//            }
//        }
    }

    @Override
    public void formatLinkAddExplain(HandlerExplainInLinkItemDTO handlerExplainInLinkItemDTO) throws XbbException {
        //暂时没有其他企业需要关联新建 市场活动
//        JSONObject linkFormData = handlerExplainInLinkItemDTO.getLinkFormData();
//        Long linkDataId = handlerExplainInLinkItemDTO.getLinkDataId();
//        List<FieldAttrEntity> explainList = handlerExplainInLinkItemDTO.getExplainList();
//        FieldAttrEntity linkCustomerField = new FieldAttrEntity();
//        FieldAttrEntity linkContactField = new FieldAttrEntity();
//        for(FieldAttrEntity fieldAttrEntity :explainList) {
//            if (Objects.equals(fieldAttrEntity.getAttr(), SalesOpportunityEnum.CUSTOMER_NAME.getAttr())) {
//                linkCustomerField = fieldAttrEntity;
//            }
//            if (Objects.equals(fieldAttrEntity.getAttr(), SalesOpportunityEnum.CONTACT_NAME.getAttr())) {
//                linkContactField = fieldAttrEntity;
//            }
//        }
//        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(handlerExplainInLinkItemDTO.getLinkBusinessType());
//        switch (redundantTemplateTypeEnum) {
//            case CUSTOMER:
//                String customerName = FastJsonHelper.getStringOrDefaultFromFormData(linkFormData, CustomerManagementEnum.NAME.getAttr(), "");
//                linkCustomerField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(linkDataId, customerName));
//                break;
//            case CONTACT:
//                String contactName = FastJsonHelper.getStringOrDefaultFromFormData(linkFormData, ContactEnum.NAME.getAttr(), "");
//                linkContactField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(linkDataId, contactName));
//                JSONArray linkCustomerArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(linkFormData, ContactEnum.CUSTOMER_NAME.getAttr(), new JSONArray());
//                linkCustomerField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(linkCustomerArr));
//                break;
//            default:
//                break;
//        }
    }

    @Override
    public FormDataAddDTO formatExcelValue(ImportFormDataDTO importFormDataDTO, List<CellTitlePojo> titlePojoList, RowGroupPojo rowGroupPojo, List<FieldAttrEntityForImport> fieldAttrList) throws XbbException {
        FormDataAddDTO formDataAddDTO = new FormDataAddDTO();
        BeanUtil.copyProperties(importFormDataDTO, formDataAddDTO);
        formDataAddDTO.setSerialNo("");
        JSONObject dataJson = new JSONObject();
        List<List<CellValuePojo>> rowValueList = rowGroupPojo.getRowValueList();
        // 分组的第一条数据作为给实体对象赋值的数据
        List<CellValuePojo> cellValueList = rowValueList.get(0);
        Map<String, FieldAttrEntity> explainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (FieldAttrEntityForImport fieldAttr : fieldAttrList) {
            String attr = fieldAttr.getAttr();
            Integer fieldType = fieldAttr.getFieldType();
            String attrName = fieldAttr.getAttrName();
            Integer columnIndex = importHelper.getColumnIndexByTitle(titlePojoList, attrName, null);
            Object cellValue = importHelper.getValueByColumnIndex(cellValueList, columnIndex);
            if (Objects.equals(fieldType, FieldTypeEnum.SUB_FORM.getType())) {
                importHelper.formatSubFormValue4Import(rowValueList, titlePojoList, importFormDataDTO, fieldAttr, dataJson);
            } else {
                if (Objects.isNull(cellValue) || StringUtil.isEmpty(cellValue.toString())) {
                    continue;
                }
                if (ImportHelper.commonHandleFieldType.contains(fieldAttr.getFieldType())) {
                    importHelper.formatCommonField(dataJson, fieldAttr, cellValue);
                } else {
                    if (Objects.equals(fieldType, FieldTypeEnum.SERIALNO.getType())) {
                        formDataAddDTO.setSerialNo(cellValue.toString());
                    } else if (Objects.equals(fieldType, FieldTypeEnum.LINK_DATA.getType())) {
                        importHelper.formatLinkData(cellValue, fieldAttr, dataJson);
                    } else if (Objects.equals(fieldType, FieldTypeEnum.LINK_DATA_MULTI.getType())) {
                        importHelper.formatLinkDataMulti(cellValue, importFormDataDTO, fieldAttr, dataJson);
                    } else {
                        dataJson.put(attr, cellValue);
                    }
                }
            }
        }
        formDataAddDTO.setDataList(dataJson);
        return formDataAddDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBatchLabelAttr(AddLabelDTO addLabelDTO, List<PaasFormDataEntityExt> addBatchList, Boolean addOrDelete) throws XbbException {
        MarketActivityUpdateBatchDTO paySheetUpdateBatchDTO = new MarketActivityUpdateBatchDTO();
        BeanUtil.copyProperties(addLabelDTO, paySheetUpdateBatchDTO);
        List<MarketActivityUpdateDTO> paySheetList = new ArrayList<>();
        addBatchList.forEach(item->{
            MarketActivityUpdateDTO paySheetUpdateDTO= new MarketActivityUpdateDTO();
            paySheetUpdateDTO.setData(item.getData());
            paySheetUpdateDTO.setId(item.getId());
            paySheetList.add(paySheetUpdateDTO);
        });
        paySheetUpdateBatchDTO.setMarketActivityList(paySheetList);
        marketActivityUpdateBatch(paySheetUpdateBatchDTO);

    }

    @Override
    public MarketActivitySearchVO getMarketName(MarketActivitySearchDTO marketActivitySearchDTO) throws XbbException {

        MarketActivitySearchVO marketActivitySearchVO = new MarketActivitySearchVO();
        //查询信息
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        //基础参数
        PaasFormEntityExt byBusinessType = paasFormModel.getByBusinessType(XbbRefTypeEnum.MARKET_ACTIVITY.getCode(), marketActivitySearchDTO.getCorpid());
        if(byBusinessType==null){
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018.getCode(), I18nStringConstant.FORM_NOT_EXIST);
        }
        // 可以很魔性的查询列表页找不到的数据,这是我最后的倔强了
        boolQueryBuilder.filter(termQuery("corpid.keyword", marketActivitySearchDTO.getCorpid()));
        boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termQuery("appId", byBusinessType.getAppId()));
        boolQueryBuilder.filter(termQuery("formId", byBusinessType.getId()));
        boolQueryBuilder.filter(termsQuery("flowStatus", FlowStatusEnum.getStatisticType()));
        //产品名称
        String nameAttr = MarketActivityEnum.NAME.getAttr();
        String nameField = "data." + nameAttr;

        List<SortBuilder> sortBuilderList = new ArrayList<>();
        sortBuilderList.add(new FieldSortBuilder("addTime").order(SortOrder.DESC));
        String nameOrNoLike = marketActivitySearchDTO.getNameOrNoLike();
        //产品名称或编号模糊查询
        if (StringUtil.isNotEmpty(nameOrNoLike)) {
            QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery(nameField, nameOrNoLike);
            boolQueryBuilder.should(queryBuilder);
            boolQueryBuilder.minimumShouldMatch(EsNormalConstant.MINI_MUM_SHOULD_MATCH);
        }
        //需要查出的字段
        List<String> fieldList = Arrays.asList("dataId", nameField, "addTime");
        //TODO 做成分页查询
        Integer page = marketActivitySearchDTO.getPage();
        Integer pageSize = marketActivitySearchDTO.getPageSize();
        String platform = marketActivitySearchDTO.getPlatform();
        if (Objects.equals(platform, PlatFormEnum.DINGTALK.getValue()) && pageSize == null) {
            pageSize = PageConstant.DEFAULT_PAGE_SIZE;
        } else if (Objects.equals(platform, PlatFormEnum.WEB.getValue()) && pageSize == null) {
            pageSize = PageConstant.DEFAULT_PAGE_SIZE_SMALL;
        }
        List<PaasFormDataEntity> paasFormDataEntities = new ArrayList<>();
        XbbAggregatedPage esEntities = esHelper.findByPage(IndexTypeEnum.IDX_SAAS_MARKET_ACTIVITY, boolQueryBuilder, PaasFormDataEntity.class, fieldList, page, pageSize, sortBuilderList);
        int rowCounts = 0;
        if (esEntities != null) {
            paasFormDataEntities = esEntities.getContent();
            rowCounts = (int) esEntities.getTotalElements();
        }
        //设置分页相关信息
        PageHelper pageHelper = PageHelperUtil.initPageHelper(rowCounts, page, pageSize, pageSize);
        marketActivitySearchVO.setPageHelper(pageHelper);
        JSONArray json = new JSONArray();
        paasFormDataEntities.forEach(item->{
            JSONObject object = new JSONObject();
            object.put("marketName", item.getData().getString(MarketActivityEnum.NAME.getAttr()));
            object.put("id", item.getDataId());
            json.add(object);
        });

        marketActivitySearchVO.setMarketList(json);
        return marketActivitySearchVO;
    }

    @Override
    public void afterSaveForWorkflow(SaasFormSaveDTO saasFormSaveDTO) throws XbbException {
        PaasFormDataEntity newPaasFormDataEntity = saasFormSaveDTO.getNewPaasFormDataEntity();
        Long dataId = newPaasFormDataEntity.getId();

        // 团队保存
        teamDataHelp.saveUserTeam(saasFormSaveDTO.getSaasNeedRedundantAttrPoJo(), dataId, newPaasFormDataEntity, saasFormSaveDTO.getIsImport(), true);

        //保存团队
//        SaasNeedRedundantAttrPojo saasNeedRedundantAttrPoJo = saasFormSaveDTO.getSaasNeedRedundantAttrPoJo();
//        if (Objects.nonNull(saasNeedRedundantAttrPoJo)) {
//            BeforeSaveMyTeamDTO beforeSaveMyTeamDTO = saasNeedRedundantAttrPoJo.getBeforeSaveMyTeamDTO();
//            beforeSaveMyTeamDTO.setDataId(dataId);
//            UserTeamBatchSaveDTO userTeamBatchSaveDTO = userTeamService.beforeSaveMyTeam(beforeSaveMyTeamDTO);
//            userTeamBatchSaveDTO.setLoginUser(saasFormSaveDTO.getLoginUser());
//            userTeamService.saveMyTeam(userTeamBatchSaveDTO);
//        }


    }

    @Override
    public void afterSaveForUpdateWorkflow(SaasFormSaveDTO saasFormSaveDTO) throws XbbException {
        PaasFormDataEntity newPaasFormDataEntity = saasFormSaveDTO.getNewPaasFormDataEntity();
        Long dataId = newPaasFormDataEntity.getId();

        //保存团队
        SaasNeedRedundantAttrPojo saasNeedRedundantAttrPoJo = saasFormSaveDTO.getSaasNeedRedundantAttrPoJo();
        if (Objects.nonNull(saasNeedRedundantAttrPoJo)) {
            // 团队保存
            teamDataHelp.saveUserTeam(saasFormSaveDTO.getSaasNeedRedundantAttrPoJo(), dataId, newPaasFormDataEntity, saasFormSaveDTO.getIsImport(), true);
        }


    }
}
